package com.example.netty.C2C.server.handler;


import com.example.netty.C2C.protocol.request.MessageRequestPacket;
import com.example.netty.C2C.protocol.response.MessageResponsePacket;
import com.example.netty.C2C.session.Session;
import com.example.netty.C2C.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
 * @author liupk
 * @date 2018/10/24
 */
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) {
        /**拿到消息发送方的会话信息*/
        Session session = SessionUtil.getSession(ctx.channel());

        /**通过消息发送方的会话信息构造要发送的消息*/
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setFromUserName(session.getUserName());
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());

        /**拿到消息接收方的 channel*/
        Channel toUserChannel = SessionUtil.getChannel(messageRequestPacket.getToUserId());

        /**将消息发送给消息接收方*/
        if (toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(messageResponsePacket);
        } else {
            System.err.println("[" + messageRequestPacket.getToUserId() + "] 不在线，发送失败!");
        }
    }
}
